package org.opens.factory.lottery.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.PageResult;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import org.opens.dao.LotteryHistoryDao;
import org.opens.entity.LotteryHistory;
import org.opens.entity.LotteryTicket;
import org.opens.entity.vo.WinningInfo;
import org.opens.entity.vo.WinningInfoCode;
import org.opens.factory.lottery.LotteryApi;
import org.opens.factory.lottery.other.LotteryTypes;
import org.opens.service.impl.LotteryHistoryServiceImpl;
import org.opens.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component
public class JuHeLotteryApiImpl implements LotteryApi {

    @Autowired
    private LotteryHistoryDao lotteryHistoryDao;

    private static final String RESULT_QUERY_URL = "http://apis.juhe.cn/lottery/query";

    private static final String HISTORY_QUERY_URL = "http://apis.juhe.cn/lottery/history";

    private static final String DECIDE_IF_WIN_THE_LOTTERY = "http://apis.juhe.cn/lottery/bonus";

    private static final String KEY = "3f84ac12a484104fac40b22655906361";

    @Autowired
    private LotteryHistoryServiceImpl lotteryHistoryService;

    @Override
    public LotteryHistory resultQuery(String type, String numOfPeriods) {
        Map<String, Object> param = new HashMap<>();
        param.put("key", KEY);
        if (StrUtil.isBlank(type)) {
            param.put("lottery_id", LotteryTypes.SSQ);
        }
        if (StrUtil.isNotBlank(numOfPeriods)) {
            param.put("lottery_no", numOfPeriods);
        }
        String historyResult = HttpUtil.get(RESULT_QUERY_URL, param);
        JSONObject jsonObject = new JSONObject(historyResult);
        Integer errorCode = jsonObject.getInt("error_code");
        if (errorCode != 0) {
            throw new RuntimeException(jsonObject.getStr("reason"));
        }

        LotteryHistory lotteryHistory = new LotteryHistory();
        JSONObject result = jsonObject.getJSONObject("result");

        String lotteryRes = result.getStr("lottery_res");
        String[] lotteryResSplit = lotteryRes.split(",");
        lotteryHistory.setRedNum1(Integer.valueOf(lotteryResSplit[0]));
        lotteryHistory.setRedNum2(Integer.valueOf(lotteryResSplit[1]));
        lotteryHistory.setRedNum3(Integer.valueOf(lotteryResSplit[2]));
        lotteryHistory.setRedNum4(Integer.valueOf(lotteryResSplit[3]));
        lotteryHistory.setRedNum5(Integer.valueOf(lotteryResSplit[4]));
        lotteryHistory.setRedNum6(Integer.valueOf(lotteryResSplit[5]));
        lotteryHistory.setBlueNum(Integer.valueOf(lotteryResSplit[6]));

        lotteryHistory.setNumOfPeriods(result.getStr("lottery_no"));
        lotteryHistory.setType(result.getStr("lottery_id"));
        lotteryHistory.setDrawDate(result.getDate("lottery_date"));
        lotteryHistory.setExDate(result.getDate("lottery_exdate"));

        JSONArray lotteryPrize = result.getJSONArray("lottery_prize");
        JSONObject jsonObject1 = null;
        JSONObject jsonObject2 = null;
        JSONObject jsonObject3 = null;
        JSONObject jsonObject4 = null;
        JSONObject jsonObject5 = null;
        JSONObject jsonObject6 = null;
        if (lotteryPrize.size() <= 6) {
            jsonObject1 = lotteryPrize.getJSONObject(0);
            jsonObject2 = lotteryPrize.getJSONObject(1);
            jsonObject3 = lotteryPrize.getJSONObject(2);
            jsonObject4 = lotteryPrize.getJSONObject(3);
            jsonObject5 = lotteryPrize.getJSONObject(4);
            jsonObject6 = lotteryPrize.getJSONObject(5);
        } else {
            // 用来跳过一等奖普惠奖和一等奖特别奖
            final int OFFSET = 2;
            jsonObject1 = lotteryPrize.getJSONObject(0);
            jsonObject2 = lotteryPrize.getJSONObject(1 + OFFSET);
            jsonObject3 = lotteryPrize.getJSONObject(2 + OFFSET);
            jsonObject4 = lotteryPrize.getJSONObject(3 + OFFSET);
            jsonObject5 = lotteryPrize.getJSONObject(4 + OFFSET);
            jsonObject6 = lotteryPrize.getJSONObject(5 + OFFSET);
        }
        lotteryHistory.setFirstPriceNum(jsonObject1.getInt("prize_num"));
        lotteryHistory.setSecondPriceNum(jsonObject2.getInt("prize_num"));
        lotteryHistory.setThirdPriceNum(jsonObject3.getInt("prize_num"));
        lotteryHistory.setFourthPriceNum(jsonObject4.getInt("prize_num"));
        lotteryHistory.setFifthPriceNum(jsonObject5.getInt("prize_num"));
        lotteryHistory.setSixthPriceNum(jsonObject6.getInt("prize_num"));

        return lotteryHistory;
    }

    @Override
    public PageResult<LotteryHistory> historyQuery(String type, int pageSize, int pageNumber) {
        if (StrUtil.isEmpty(type)) {
            type = LotteryTypes.SSQ;
        }

        Map<String, Object> param = new HashMap<>();
        param.put("key", KEY);
        param.put("lottery_id", type);
        param.put("page", pageNumber);
        param.put("page_size", pageSize);

        String getResult = HttpUtil.get(HISTORY_QUERY_URL, param);
        JSONObject jsonObject = new JSONObject(getResult);
        Integer errorCode = jsonObject.getInt("error_code");
        if (errorCode != 0) {
            throw new RuntimeException(jsonObject.getStr("reason"));
        }

        JSONObject pageResult = jsonObject.getJSONObject("result");
        PageResult<LotteryHistory> result = new PageResult<>();
        JSONArray lotteryResList = pageResult.getJSONArray("lotteryResList");
        if (CollectionUtil.isNotEmpty(lotteryResList)) {
            for (int i = 0; i < lotteryResList.size(); i++) {
                JSONObject jsonObject1 = lotteryResList.getJSONObject(i);
                LotteryHistory lotteryHistory = new LotteryHistory();
                lotteryHistory.setType(jsonObject1.getStr("lottery_id"));
                lotteryHistory.setNumOfPeriods(jsonObject1.getStr("lottery_no"));
                lotteryHistory.setDrawDate(jsonObject1.getDate("lottery_date"));
                lotteryHistory.setExDate(jsonObject1.getDate("lottery_exdate"));
                String[] ticketNumArr = jsonObject1.getStr("lottery_res").split(",");
                lotteryHistory.setRedNum1(Integer.valueOf(ticketNumArr[0]));
                lotteryHistory.setRedNum2(Integer.valueOf(ticketNumArr[1]));
                lotteryHistory.setRedNum3(Integer.valueOf(ticketNumArr[2]));
                lotteryHistory.setRedNum4(Integer.valueOf(ticketNumArr[3]));
                lotteryHistory.setRedNum5(Integer.valueOf(ticketNumArr[4]));
                lotteryHistory.setRedNum6(Integer.valueOf(ticketNumArr[5]));
                lotteryHistory.setBlueNum(Integer.valueOf(ticketNumArr[6]));
                result.add(lotteryHistory);
            }
        }

        result.setPage(pageResult.getInt("page"));
        result.setPageSize(pageResult.getInt("pageSize"));
        result.setTotalPage(pageResult.getInt("totalPage"));

        return result;
    }

    @Override
    public Map<LotteryTicket, WinningInfo> decideIfWinTheLottery(List<LotteryTicket> lotteryTickets) {
        if (CollectionUtil.isEmpty(lotteryTickets)) {
            return null;
        }
        Map<LotteryTicket, WinningInfo> result = new HashMap<>();

        for (LotteryTicket lotteryTicket : lotteryTickets) {
            WinningInfo winningInfo = new WinningInfo();
            Map<String, Object> param = new HashMap<>();
            if (!lotteryTicket.isEffective()) {
                winningInfo.setCode(WinningInfoCode.ERROR.value);
                winningInfo.setWinningMessage(WinningInfoCode.ERROR.message);
                winningInfo.setWinningFlag(false);
                result.put(lotteryTicket, winningInfo);
                continue;
            }
            if (StrUtil.isNotEmpty(lotteryTicket.getType()) && !Objects.equals(lotteryTicket.getType(), LotteryTypes.SSQ)) {
                throw new RuntimeException("目前只支持双色球");
            }
            param.put("lottery_id", LotteryTypes.SSQ);
            param.put("lottery_no", StrUtil.isEmpty(lotteryTicket.getNumOfPeriods()) ? "" : lotteryTicket.getNumOfPeriods());
            param.put("key", KEY);
            param.put("lottery_res", lotteryTicket.getTicketNumber());
            String resultTemp = HttpUtil.get(DECIDE_IF_WIN_THE_LOTTERY, param);
            JSONObject jsonObject = new JSONObject(resultTemp);
            Integer errorCode = jsonObject.getInt("error_code");
            if (errorCode != 0) {
                winningInfo.setCode(WinningInfoCode.ERROR.value);
                winningInfo.setWinningMessage(jsonObject.getStr("reason"));
                winningInfo.setWinningFlag(false);
                result.put(lotteryTicket, winningInfo);
                continue;
            }
            JSONObject innerResult = jsonObject.getJSONObject("result");
            winningInfo.setWinningFlag(innerResult.getInt("is_prize") == 1);
            winningInfo.setWinningMessage(innerResult.getStr("prize_msg"));
            winningInfo.setCode(WinningInfoCode.NORMAL.value);
            result.put(lotteryTicket, winningInfo);
        }
        return result;
    }

}
